package com.example.gatewayservice.filter;

import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.util.Arrays;
import java.util.List;

/**
 * 全局认证过滤器
 */
@Component
public class GlobalAuthFilter implements GlobalFilter, Ordered {

    // 不需要认证的路径
    private static final List<String> WHITE_LIST = Arrays.asList(
            "/user/register",
            "/user/login",
            "/actuator/health",
            "/actuator/info"
    );

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        ServerHttpRequest request = exchange.getRequest();
        String path = request.getPath().value();

        // 检查是否是白名单路径
        if (isWhitePath(path)) {
            return chain.filter(exchange);
        }

        // 获取Authorization头
        String token = request.getHeaders().getFirst("Authorization");

        if (!StringUtils.hasText(token) || !token.startsWith("Bearer ")) {
            exchange.getResponse().setStatusCode(HttpStatus.UNAUTHORIZED);
            return exchange.getResponse().setComplete();
        }

        // 提取token
        String jwtToken = token.substring(7);

        // 这里可以添加JWT验证逻辑
        // 暂时简单验证token不为空
        if (!StringUtils.hasText(jwtToken)) {
            exchange.getResponse().setStatusCode(HttpStatus.UNAUTHORIZED);
            return exchange.getResponse().setComplete();
        }

        // 将用户信息添加到请求头中，传递给下游服务
        ServerHttpRequest modifiedRequest = request.mutate()
                .header("X-User-Id", "extracted-user-id") // 这里应该从JWT中提取用户ID
                .header("X-User-Role", "extracted-user-role") // 这里应该从JWT中提取用户角色
                .build();

        return chain.filter(exchange.mutate().request(modifiedRequest).build());
    }

    @Override
    public int getOrder() {
        return -100; // 确保在其他过滤器之前执行
    }

    /**
     * 检查是否是白名单路径
     */
    private boolean isWhitePath(String path) {
        return WHITE_LIST.stream().anyMatch(path::startsWith);
    }
}
